package com.xhapi.service.impl;

import com.google.gson.Gson;
import com.xhapi.config.XfXhConfig;
import com.xhapi.service.TranslateService;
import com.xhapi.test.WebOTS;
import com.xhapi.utils.HttpUtil;
import com.xhapi.utils.tranlateUtils.TranTools;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Map;


@Service
@RequiredArgsConstructor
@Slf4j
public class TranslateServiceimpl implements TranslateService {
    private final TranTools tranTools;
    private final XfXhConfig xfXhConfig;
    @Override
    public String translate(String from, String to, String text) throws Exception {
        if (xfXhConfig.getAppId().equals("") || xfXhConfig.getApiKey().equals("") || xfXhConfig.getApiSecret().equals("")) {
            log.info("Appid 或APIKey 或APISecret 为空！请打开demo代码，填写相关信息。");
            return null;
        }
        String body = tranTools.buildHttpBody(from,to,text);
        log.info(xfXhConfig.getApiKey());
        log.info(xfXhConfig.getAppId());
        log.info(xfXhConfig.getApiSecret());
        Map<String, String> header = tranTools.buildHttpHeader(body);
        Map<String, Object> resultMap = HttpUtil.doPost2(xfXhConfig.getTranslate(), header, body);
        if (resultMap != null) {
            String resultStr = resultMap.get("body").toString();
            System.out.println("【OTS WebAPI 接口调用结果】\n" + resultStr);
            //以下仅用于调试
            Gson json = new Gson();
            WebOTS.ResponseData resultData = json.fromJson(resultStr, WebOTS.ResponseData.class);
            int code = resultData.getCode();
            if (resultData.getCode() != 0) {
                System.out.println("请前往https://www.xfyun.cn/document/error-code?code=" + code + "查询解决办法");
            }
        } else {
            System.out.println("调用失败！请根据错误信息检查代码，接口文档：https://www.xfyun.cn/doc/nlp/niutrans/API.html");
        }
        return body;
    }
}
